<!-- 添加已有试题 -->
<template>
  <div class="add-container">
    <div class="question-list">
      <!-- 操作栏 -->
      <el-form ref="actionForm" :inline="true" label-position="right" label-width="auto" @submit.native.prevent>
        <el-row>
          <el-col :span="24">
            <el-form-item :label="$t('questionLangList.tags')">
              <el-select v-model="tagsData" :placeholder="$t('paperQuestionLangList.tagsTooltip')" value-key="id" filterable multiple style="width: 300px" @change="tagsChange">
                <el-option v-for="item in allTagsArr" :key="item.id" :label="item.title" :value="item"/>
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('questionLangList.keyword')">
              <el-input :placeholder="$t('questionLangList.keywordTip')" v-model="conditionForm.title"/>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="searchQuestion">{{ $t('table.search') }}</el-button>
            </el-form-item>
            <el-form-item>
              <span>注：可通过选择标签来筛选出需要的题目，标签可多选</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 列表栏 -->
      <div class="grid-content">
        <el-table v-loading="listLoading" ref="dataListRef" :key="tableKey" :data="paperQuestionList" :element-loading-text="$t('table.loadingText')" @selection-change="questionSelectChange" border fit stripe highlight-current-row>
          <el-table-column type="selection" width="50">
          </el-table-column>
          <el-table-column :label="$t('table.id')" type="index" width="50" align="center"/>
          <el-table-column :label="$t('paperQuestionLangList.question')" align="center">
            <template slot-scope="scope">
              <span class="subjectSpan" v-html="scope.row.groupSubjectTxt"/>
              <audio v-if="scope.row.groupSubjectAudio" controls>
                <source :src="scope.row.groupSubjectAudio" type="audio/mpeg">
              </audio>
            </template>
          </el-table-column>
          <el-table-column :label="$t('paperQuestionLangList.questionType')" align="center" prop="title" width="120">
            <template slot-scope="scope">
              <span v-if="scope.row.category !== ''">{{ questionTypeArr.find(v => v.value === scope.row.category).label }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('table.actions')" align="center" width="260">
            <template slot-scope="scope">
              <el-button type="text" @click="goToPreview(scope.row)">{{ $t('table.preview') }}</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-container">
          <el-pagination :current-page="conditionForm.page" :page-sizes="[5,10,50,100,150,200]" :page-size="conditionForm.pageSize" :total="dataTotal" background layout="total, sizes, prev, pager, next, jumper" @size-change="dataSizeChange" @current-change="dataCurrentChange"/>
        </div>
      </div>
    </div>
    <div class="footer-btn">
      <el-row type="flex" justify="center">
        <el-button type="primary" @click="savePaperQuestion">{{ $t('paperQuestionLangList.confirmSelect') }}</el-button>
        <el-button @click="cancelAddExisting">{{ $t('form.cancel') }}</el-button>
      </el-row>
    </div>
  </div>
</template>

<script>
  import { getPaperQuestion, publishPaper, updatePaperQuestion } from '@/api/paper'
  import { createTag, getTagList, removeTag, updateTag } from '@/api/tags'
  import { getQuestionData, removeQuestion } from '@/api/question'
  import tagsCom from './paperTags'
  import updateQuestionCom from './paperUpdateQuestion'
  import { cates } from '@/utils/dic'
  import { removeArray } from '@/utils'
  export default {
    name: 'AddExistingQuestion',
    props: {
      paperId: String
    },
    components: {
      tagsCom,
      updateQuestionCom
    },
    data() {
      return {
        id: '',
        tableKey: 0,
        listLoading: false,
        conditionForm: {
          page: 1,
          pageSize: 10,
          title: '',
          labelIds: ''
        },
        dataTotal: 0,
        paperQuestionList: [],
        dialogTagsVisible: false,
        questionTypeArr: [],
        dialogNewQuestionVisible: false,
        dialogUpdateQuestionVisible: false,
        dialogTagsManageVisible: false,
        qId: '',
        selectQuestionArray: [],
        allTagsArr: [],
        tagsData: [],
        inputVisible: false,
        addTagForm: {
          title: '',
          category: 'question'
        }
      }
    },
    created() {
      this.questionTypeArr = cates
      this.id = this.$route.query && this.$route.query.id
      this.initTagsData()
    },
    methods: {
      // 初始化标签数据
      initTagsData() {
        const _this = this
        getTagList({ title: '' }).then(res => {
          _this.allTagsArr = res
        })
      },
      // 选择试题监听事件
      questionSelectChange(rows) {
        this.selectQuestionArray = rows
      },
      // 获取试题列表
      getPageDataList() {
        const _this = this
        _this.paperQuestionList = []
        // _this.dataTotal = 0
        if (_this.conditionForm.title === '' && _this.conditionForm.labelIds.length === 0) {
          this.$message({
            message: '搜索条件不能为空',
            type: 'warning'
          })
        } else {
          _this.listLoading = true
          getQuestionData(_this.conditionForm).then(res => {
            _this.listLoading = false
            if (res) {
              _this.paperQuestionList = res.items
              _this.dataTotal = res.total
            }
          }).catch(err => {
            _this.listLoading = false
            console.info(err)
          })
        }
      },
      // 标签选择框选择事件
      tagsChange(val) {
        let tagsIds = []
        val.forEach(v => {
          tagsIds.push(v.id)
        })
        this.conditionForm.page = 1
        this.conditionForm.labelIds = tagsIds
        this.getPageDataList()
      },
      // 搜索
      searchQuestion() {
        let tagsIds = []
        this.tagsData.forEach(v => {
          tagsIds.push(v.id)
        })
        this.conditionForm.page = 1
        this.conditionForm.labelIds = tagsIds
        this.getPageDataList()
      },
      dataSizeChange(val) {
        this.conditionForm.pageSize = val
        this.getPageDataList()
      },
      // 翻页
      dataCurrentChange(val) {
        this.conditionForm.page = val
        this.getPageDataList()
      },
      // 试题预览
      goToPreview(row) {
        this.$router.push({
          path: '/preview/index',
          query: {
            id: row.id,
            type: 'question',
            t: +new Date()
          }
        })
      },
      // 确定选入
      savePaperQuestion() {
        if (this.selectQuestionArray.length === 0) {
          this.$message({
            message: '请选择要选入的试题',
            type: 'warning'
          })
        } else {
          const _this = this
          let idArray = []
          _this.selectQuestionArray.forEach(v => {
            idArray.push(v.id)
          })
          const postData = {
            questionIds: idArray.join(',')
          }
          updatePaperQuestion(_this.paperId, postData).then(res => {
            if (res) {
              _this.$message({
                message: '保存成功',
                type: 'success'
              })
              _this.$emit('successCallback')
            }
          })
        }
      },
      // 取消
      cancelAddExisting() {
        this.$emit('cancelCallback')
      }
    }
  }
</script>

<style lang="less" scoped>
  .add-container {
    height: 420px;
    .question-list {
      height: 360px;
      overflow-y: auto;
    }
    .footer-btn {
      display: flex;
      justify-content: center;
      padding: 20px;
      position: absolute;
      bottom: 0;
      width: 100%;
    }
  }
  .subjectSpan img {
    height: 130px;
  }
  .tags-manage .top-title {
    margin-bottom: 20px;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
  .tag-list {
    margin-top: 20px;
    .el-tag {
      margin-right: 10px;
      margin-bottom: 10px;
    }
  }
</style>
